<template>
  <div class="message-container" ref="messageContainer">
    <MessageArea
      title="留言板"
      :subTitle="`(${record.total})`"
      :isListLoading="isLoading"
      :list="record.rows"
      @submit="handleSubmit"
    />
  </div>
</template>

<script>
import MessageArea from '@/components/MessageArea'
import fetchData from '@/mixins/fetchData.js'
import { getMessages, postMessage } from '../../api'
import mainScroll from '@/mixins/mainScroll.js'
export default {
  name: 'index',
  components: {
    MessageArea
  },
  data () {
    return {
      page: 1,
      limit: 10
    }
  },
  mixins: [fetchData({ total: 0, rows: [] }), mainScroll('messageContainer')],
  created () {
    this.$bus.$on('mainScroll', this.handleScroll)
  },
  destroyed () {
    this.$bus.$off('mainScroll', this.handleScroll)
  },
  computed: {
    hasMore () {
      return this.record.rows.length < this.record.total
    }
  },
  methods: {
    async fetchData () {
      return getMessages({
        page: this.page,
        limit: this.limit
      })
    },
    async handleScroll (dom) {
      if (!this.isLoading || !dom) {
        return
      }
      const range = 100 // 可控范围内
      const dec = Math.abs((dom.scrollTop + dom.clientHeight) - dom.scrollHeight)
      if (dec <= range) {
        await this.fetchMore()
      }
    },
    // 加载下一页
    async fetchMore () {
      if (!this.hasMore) {
        return
      }
      this.isLoading = false
      this.page++
      const resp = await this.fetchData()
      this.record.total = resp.total
      this.record.rows = this.record.rows.concat(resp.rows)
      this.isLoading = true
    },
    async handleSubmit (data, callback) {
      const resp = await postMessage(data)
      // eslint-disable-next-line standard/no-callback-literal
      callback('感谢您的留言')
      this.record.rows.unshift(resp)
    }
  }
}
</script>

<style scoped>
  .message-container {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    padding: 25px 0;
    box-sizing: border-box;
    scroll-behavior: smooth;
  }
  .message-area-container {
    width: 700px;
    margin: 0 auto;
  }
</style>
